package controllers

import (
	"context"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/redis/go-redis/v9"
	"shang/models"
	"strconv"
	"time"
)

type TypeTopController struct {
	beego.Controller
}

func (s *TypeTopController) TypeTop() {
	typeId := s.GetString("type")
	exists := models.Redis.Exists(context.Background(), "video_type:"+typeId).Val()
	if exists != 0 {
		result := models.Redis.ZRevRange(context.Background(), "video_type"+typeId, 0, 10).Val()
		var videoDataAll []models.Video
		for _, v := range result {
			var video models.Video
			json.Unmarshal([]byte(v), &video)
			videoDataAll = append(videoDataAll, video)
		}
		s.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "success",
			"data": videoDataAll,
		}
		s.ServeJSON()
		return
	}
	id, _ := strconv.Atoi(typeId)
	top, _ := models.GetTopInfo(models.Video{
		TypeId: id,
	})
	for _, v := range top {
		marshal, _ := json.Marshal(v)
		models.Redis.ZAdd(context.Background(), "video_type"+typeId, redis.Z{
			Score:  float64(v.Attendance),
			Member: string(marshal),
		})
		err := models.Redis.Expire(context.Background(), "video_type"+typeId, time.Minute*10).Err()
		if err != nil {
			s.Data["json"] = map[string]interface{}{
				"code": 400,
				"msg":  "添加过期时间失败",
			}
			s.ServeJSON()
			return
		}
	}
	s.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
		"data": top,
	}
	s.ServeJSON()
}
